// 屏幕捕获核心功能
class ScreenshotCore {
	constructor() {
		// 获取DOM元素引用
		this.stream = null;
	}

	// 开始屏幕捕获
	async startCapture() {
		try {
			this.stream = await navigator.mediaDevices.getDisplayMedia({ video: true });

			video.srcObject = this.stream;
			videoContainer.style.display = 'block';
			canvasWrapper.style.display = 'none';
			startBtn.disabled = true;
			captureBtn.disabled = false;

			screenshotToolCard.style.display = 'none';
			// 当视频可以播放时调整canvas大小
			video.addEventListener('loadedmetadata',
				() => {
					canvas.width = video.videoWidth;
					canvas.height = video.videoHeight;
				}
			);
		}
		catch (err) {
			console.error("Error: " + err);
			alert('无法捕获屏幕: ' + err.message);
		}
	}

	// 计算缩放比例
	calculateScale() {
		const rect = canvas.getBoundingClientRect();
		return {
			scaleX: canvas.width / rect.width,
			scaleY: canvas.height / rect.height
		};
	}

	// 捕获当前屏幕到canvas
	captureScreen() {
		canvasCtx.drawImage(video, 0, 0, canvas.width, canvas.height);

		// 停止视频流
		if (this.stream) this.stream.getTracks().forEach(track => track.stop());

		videoContainer.style.display = 'none';
		canvasWrapper.style.display = 'block';
		downloadBtn.disabled = false;
		undoBtn.disabled = false;
		captureBtn.disabled = true;
		startBtn.disabled = false;
		screenshotToolCard.style.display = 'block';
	}

	// 下载图片（保存到服务器）
	async downloadImage() {
		// 创建一个临时canvas来合并两个图层
		const tempCanvas = document.createElement('canvas');
		tempCanvas.width = canvas.width;
		tempCanvas.height = canvas.height;
		const tempCtx = tempCanvas.getContext('2d');

		// 先绘制截图
		tempCtx.drawImage(canvas, 0, 0);
		// 再绘制绘制层
		tempCtx.drawImage(drawCanvas, 0, 0);

		// 将canvas转换为Blob对象
		const blob = await new Promise(resolve => { tempCanvas.toBlob(resolve, 'image/png'); });

		// 创建文件名
		const fileName = 'screenshot-' + new Date().toISOString().replace(/:/g, '-') + '.png';

		// 创建File对象
		const file = new File([blob], fileName, { type: 'image/png' });

		// 调用saveImageToServer函数保存图片到服务器
		await saveImageToServer(file);

		// 显示保存成功的提示
		showSystemMessage('图片[' + 'images/' + fileName + ']已保存', 'success');
	}

	// 获取合并图层后的图片文件数据，用于视觉识别
	getMergedImageData() {
		// 创建一个临时canvas来合并两个图层
		const tempCanvas = document.createElement('canvas');
		tempCanvas.width = canvas.width;
		tempCanvas.height = canvas.height;
		const tempCtx = tempCanvas.getContext('2d');

		// 先绘制截图
		tempCtx.drawImage(canvas, 0, 0);
		// 再绘制绘制层
		tempCtx.drawImage(drawCanvas, 0, 0);

		// 返回base64格式的图片数据
		return tempCanvas.toDataURL('image/png');
	}

	// 重置工具
	resetTool(drawCanvas, previewCanvas, drawCtx, previewCtx, historyManager) {
		if (this.stream) {
			this.stream.getTracks().forEach(track => track.stop());
		}

		videoContainer.style.display = 'none';
		canvasWrapper.style.display = 'none';
		downloadBtn.disabled = true;
		undoBtn.disabled = true;
		captureBtn.disabled = true;
		startBtn.disabled = false;

		canvasCtx.clearRect(0, 0, canvas.width, canvas.height);
		drawCtx.clearRect(0, 0, drawCanvas.width, drawCanvas.height);
		previewCtx.clearRect(0, 0, previewCanvas.width, previewCanvas.height);

		// 使用historyManager的clear方法而不是直接操作actionHistory
		historyManager.clear();
	}
}